package com.qf.medicaldoctoradmin.healthMonitor.details.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.common.entity.Monitor;
import com.qf.common.entity.MonitorRule;
import com.qf.common.enums.MonitorRuleEnum;
import com.qf.common.utils.CopyNotNullUtils;
import com.qf.common.utils.RedisUtils;
import com.qf.common.utils.UserUtils;
import com.qf.medicaldoctoradmin.healthMonitor.details.dao.DetailsDao;
import com.qf.medicaldoctoradmin.healthMonitor.details.service.DetailsService;
import com.qf.medicaldoctoradmin.healthMonitor.details.vo.DetailsVO;
import com.qf.medicaldoctoradmin.healthMonitor.monitor.dao.MonitorDao;
import com.qf.medicaldoctoradmin.healthMonitor.monitor.service.MonitorService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DetailsServiceImpl implements DetailsService {
    @Resource
    private DetailsDao detailsDao;

    @Resource
    private MonitorDao monitorDao;

    @Resource
    private MonitorService monitorService;

    @Lazy
    @Resource
    private DetailsService detailsService;


    @Override
    public List<Monitor> getDetails() {
        List<Monitor> monitors = monitorService.selectList();
        if (monitors == null) {
            throw new RuntimeException("空空如也");
        }
        return monitors;
    }

    @Override
    public void insert(Monitor monitor) {
        if (monitor.getWeight() == null) {
            throw new RuntimeException("请先输入更新信息");
        }
        Monitor oldMonitor = monitorService.selectOne();
        oldMonitor.setId(null);
        CopyNotNullUtils.copyNonNullProperties(oldMonitor, monitor);
        monitor.setMonitorDate(new Date());

        monitorDao.insert(monitor);
    }

    @Override
    public DetailsVO getDoctor() {
        Integer uid = UserUtils.getUid();
        DetailsVO doctor = detailsDao.selectDoctor(uid);
        if (doctor == null) {
            throw new RuntimeException("暂未找到合适的签约医生，请先签约医生");
        }
        return doctor;
    }

    @Override
    public List<MonitorRule> getRule() {
        List<MonitorRule> rule = (List<MonitorRule>)RedisUtils.getValue(MonitorRuleEnum.MONITOR_RULE_INFO.getKey());
        if (rule == null) {
            rule = detailsDao.selectList(
                    new LambdaQueryWrapper<MonitorRule>()
                            .orderByDesc(MonitorRule::getCreateTime)
                            .last("LIMIT 1"));
            RedisUtils.setValueTimeout(MonitorRuleEnum.MONITOR_RULE_INFO.getKey(), rule, MonitorRuleEnum.MONITOR_RULE_INFO.getTimeout());
        }
        return rule;
    }

    public Map<String, String> chargeByRule() {
        HashMap<String, String> map = new HashMap<>();
        List<MonitorRule> rules = detailsService.getRule();
        // 取出一条规则
        MonitorRule rule = rules.get(0);

        // 解析血糖规则
        String bloodSugar = rule.getBloodSugarLevelRule();
        JSONArray bloodSugarArray = JSON.parseArray(bloodSugar);

        // 餐前血糖正常值范围
        JSONObject minBeforeMealRule = bloodSugarArray.getJSONObject(0).getJSONArray("餐前").getJSONObject(0);
        JSONObject maxBeforeMealRule = bloodSugarArray.getJSONObject(0).getJSONArray("餐前").getJSONObject(1);
        int minBeforeMeal = minBeforeMealRule.getInteger("最低正常值");
        int maxBeforeMeal = maxBeforeMealRule.getInteger("最高正常值");

        // 餐后血糖正常值范围
        JSONObject minAfterMealRule = bloodSugarArray.getJSONObject(1).getJSONArray("餐后").getJSONObject(0);
        JSONObject maxAfterMealRule = bloodSugarArray.getJSONObject(1).getJSONArray("餐后").getJSONObject(1);
        int minAfterMeal = minAfterMealRule.getInteger("最低正常值");
        int maxAfterMeal = maxAfterMealRule.getInteger("最高正常值");

        // 解析血压规则
        String bloodPressure = rule.getBloodPressureRule();
        JSONArray bloodPressureArray = JSON.parseArray(bloodPressure);

        // 餐前血压正常值范围
        JSONObject minHighBloodPressure = bloodPressureArray.getJSONObject(0).getJSONArray("收缩压").getJSONObject(0);
        JSONObject maxHighBloodPressure = bloodPressureArray.getJSONObject(0).getJSONArray("收缩压").getJSONObject(1);
        int minHighPressure = minHighBloodPressure.getInteger("最低正常值");
        int maxHighPressure = maxHighBloodPressure.getInteger("最高正常值");

        // 餐后血压正常值范围
        JSONObject minLowBloodPressure = bloodPressureArray.getJSONObject(1).getJSONArray("舒张压").getJSONObject(0);
        JSONObject maxLowBloodPressure = bloodPressureArray.getJSONObject(1).getJSONArray("舒张压").getJSONObject(1);
        int minLowPressure = minLowBloodPressure.getInteger("最低正常值");
        int maxLowPressure = maxLowBloodPressure.getInteger("最高正常值");

        // 解析心率规则
        String rateRule = rule.getHeartRateRule();
        JSONArray heartRateArray = JSON.parseArray(rateRule);

        // 心率正常值范围
        Integer minHeartRule = heartRateArray.getJSONObject(0).getInteger("最低正常值");
        Integer maxHeartRule = heartRateArray.getJSONObject(1).getInteger("最高正常值");

        // 获取最新监测相关数据
        Monitor monitor = monitorService.selectOne();

        // 判断血糖水平
        if (monitor.getFastingBloodGlucose() != null) {
            double fastingBloodGlucose = monitor.getFastingBloodGlucose();
            if (fastingBloodGlucose >= minBeforeMeal && fastingBloodGlucose <= maxBeforeMeal) {
                map.put("餐前血糖检测情况", "正常");
            } else {
                map.put("餐前血糖检测情况", "不正常");
            }
        } else {
            map.put("餐前血糖检测情况", "未检测");
        }

        if (monitor.getPostprandialBloodGlucose() != null) {
            double postprandialBloodGlucose = monitor.getPostprandialBloodGlucose();
            if (postprandialBloodGlucose >= minAfterMeal && postprandialBloodGlucose <= maxAfterMeal) {
                map.put("餐后血糖检测情况", "正常");
            } else {
                map.put("餐后血糖检测情况", "不正常");
            }
        } else {
            map.put("餐后血糖检测情况", "未提交数据");
        }

        // 判断体重与身高
        if (monitor.getWeight() != null && monitor.getHeight() != null) {
            // 使用 BMI 判别标准
            if (monitor.getWeight() / (monitor.getHeight() * monitor.getHeight()) > 25) {
                map.put("体重检测情况", "超重");
            } else {
                map.put("体重检测情况", "正常");
            }
        } else {
            map.put("体重检测情况", "未提交数据");
        }

        // 判断血压
        if (monitor.getHighBloodPressure() != null) {
            double highBloodPressure = monitor.getHighBloodPressure();
            if (highBloodPressure >= minHighPressure && highBloodPressure <= maxHighPressure) {
                map.put("收缩压检测情况", "正常");
            } else {
                map.put("收缩压检测情况", "不正常");
            }
        } else {
            map.put("收缩压检测情况", "未检测");
        }

        if (monitor.getLowBloodPressure() != null) {
            double lowBloodPressure = monitor.getLowBloodPressure();
            if (lowBloodPressure >= minLowPressure && lowBloodPressure <= maxLowPressure) {
                map.put("舒张压检测情况", "正常");
            } else {
                map.put("舒张压检测情况", "不正常");
            }
        } else {
            map.put("舒张压检测情况", "未提交数据");
        }

        // 判断心率
        if (monitor.getHeartRate() != null) {
            Integer heartRate = monitor.getHeartRate();
            if (heartRate >= minHeartRule && heartRate <= maxHeartRule) {
                map.put("心率检测情况", "正常");
            } else {
                map.put("心率检测情况", "不正常");
            }
        } else {
            map.put("心率检测情况", "未检测");
        }

        return map;
    }


}
